#include <stdio.h>
#include <memory.h> 

#include "cproperty.h"
extern void Output(const char * ftm, ... );
cproperty::cproperty(void)
{
}

cproperty::~cproperty(void)
{
}

int cproperty::setip(const char * card, const char* ip, const char* mask, const char* gate){
	int nRet = -1;

#ifdef WIN32
	char szcmd[1024]={0};
	sprintf(szcmd, "netsh interface ip set address \"%s\" static %s %s %s",card,ip,mask,gate);
	system( szcmd );
	::Sleep(500);
	char host_name[255];	
	if (gethostname(host_name, sizeof(host_name)) == SOCKET_ERROR) {		
		nRet = WSAGetLastError();
		Output("Error %d when getting local host name.\n", nRet);	
		return nRet;
	}
	unsigned long ipcode = inet_addr( ip );
	for( int i = 0; i<10 ; i++){	
		struct hostent *phe = gethostbyname(host_name);	
		if (phe == 0) {		
			Output("Yow! Bad host lookup.\n");			
		}		
		for (int i = 0; phe->h_addr_list[i] != 0; ++i) {		
			struct in_addr addr;		
			memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));		
			if( ipcode == inet_addr(inet_ntoa(addr)) ){
				Output("show:successall=1");
				return 0;
			}	
		}
		::Sleep(200);
	}
	Output("show:configerror=1");
#else
	int fd;
	struct ifreq ifr; 
	struct sockaddr_in *sin;
	struct rtentry  rt;
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(fd < 0)
	{
		printf("socket   error");     
		return -1;     
	}

	memset(&ifr,0,sizeof(ifr)); 
	strcpy(ifr.ifr_name,card); 
	sin = (struct sockaddr_in*)&ifr.ifr_addr;     
	sin->sin_family = AF_INET;     
	//ipaddr
	if(inet_aton(ip,&(sin->sin_addr)) < 0)   
	{     
		printf("inet_aton   error");     
		return -2;     
	}    

	if(ioctl(fd,SIOCSIFADDR,&ifr) < 0)   
	{     
		printf("ioctl   SIOCSIFADDR   error");     
		return -3;     
	}
	//netmask
	if(inet_aton(mask,&(sin->sin_addr)) < 0)   
	{
		printf("inet_pton   error");
		return -4;
	} 
	if(ioctl(fd, SIOCSIFNETMASK, &ifr) < 0)
	{
		printf("ioctl");
		return -5;
	}
	//gateway
	memset(&rt, 0, sizeof(struct rtentry));
	memset(sin, 0, sizeof(struct sockaddr_in));
	sin->sin_family = AF_INET;
	sin->sin_port = 0;

	if(inet_aton(gate, &sin->sin_addr)<0)
	{
		printf ( "inet_aton error\n" );
	}
	memcpy ( &rt.rt_gateway, sin, sizeof(struct sockaddr_in));
	((struct sockaddr_in *)&rt.rt_dst)->sin_family=AF_INET;
	((struct sockaddr_in *)&rt.rt_genmask)->sin_family=AF_INET;
	rt.rt_flags = RTF_GATEWAY;

	if (ioctl(fd, SIOCADDRT, &rt)<0)
	{
		printf( "ioctl(SIOCADDRT) error in set_default_route\n");
		close(fd);
		return -1;
	}
	close(fd);
 

#endif
	return nRet;
}

